package net.jueb.protobufs.client;
import java.util.HashMap;

import com.google.protobuf.MessageLite;

import net.jueb.protobufs.codec.ProtobufsDecoder;
import net.jueb.protobufs.codec.ProtobufsDispatcherDecoder;
import net.jueb.protobufs.codec.ProtobufsEncoder;
import net.jueb.protobufs.pojo.UsualMessageProtos;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ProtobufClient {

	
	private  HashMap<Byte,ProtobufsDecoder> decoders=new HashMap<Byte,ProtobufsDecoder>();
	{
		decoders.put((byte) 1,new ProtobufsDecoder(UsualMessageProtos.Login.getDefaultInstance()));
		decoders.put((byte) 2,new ProtobufsDecoder(UsualMessageProtos.Logout.getDefaultInstance()));
	}
	private  HashMap<Byte,MessageLite> encoders=new HashMap<Byte,MessageLite>();
	{
		encoders.put((byte) 1,UsualMessageProtos.Login.getDefaultInstance());
		encoders.put((byte) 2,UsualMessageProtos.Logout.getDefaultInstance());
	}
	
	public void connect(String ip,int port)
	{
		NioEventLoopGroup group=new NioEventLoopGroup();
		Bootstrap bt=new Bootstrap();
		bt.group(group);
		bt.channel(NioSocketChannel.class);
		bt.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				//解码器分配器
				sc.pipeline().addLast("ProtobufsDispatcherDecoder",new ProtobufsDispatcherDecoder(decoders));
				//指定编码器
				sc.pipeline().addLast("ProtobufsEncoder",new ProtobufsEncoder(encoders));
				sc.pipeline().addLast(new ProtoClientHandler());
			}
		});
		try {
			ChannelFuture cf=bt.connect(ip, port).sync();
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new ProtobufClient().connect("127.0.0.1", 80);
	}
}
